package spring.cloud.tasks.api.service.impl;

import org.apache.commons.lang3.StringUtils;
import spring.cloud.tasks.api.domain.task.ForecastCronResult;
import spring.cloud.tasks.api.service.UtilsService;
import spring.cloud.tasks.common.cron_expression.CronExpression;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.TimeZone;

public class UtilsServiceImpl implements UtilsService {

    @Override
    public ForecastCronResult checkAndForecastCron(String cronExpressionString, String pauseDatePeriod, String pauseTimePeriod)
            throws RuntimeException {

        if (StringUtils.isBlank(cronExpressionString)) {
            throw new RuntimeException("cron不能为空");
        }
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setTimeZone(TimeZone.getDefault());
        CronExpression cronExpression = null;
        cronExpression = new CronExpression(cronExpressionString, pauseDatePeriod, pauseTimePeriod);

        ForecastCronResult forecastCronResult = new ForecastCronResult();
        forecastCronResult.setCron(cronExpressionString);
        forecastCronResult.setNextFireTimes(new ArrayList<String>());
        Date now = new Date();
        for (int i = 0; i < 10; i++) {
            Date next = cronExpression.getFireTimeAfter(now);
            if (next != null) {
                forecastCronResult.getNextFireTimes().add(dateFormat.format(next));
                now = next;
            }
        }
        if (forecastCronResult.getNextFireTimes().isEmpty()) {
            throw new RuntimeException(String.format("cron(%s)可能描述的是一个过去的时间，将不会被执行", cronExpressionString));
        }
        return forecastCronResult;
    }


}
